export default class PreciseUtil {

    // 加
    public static add(value1: number, value2: number) {
        let r1 = 0, r2 = 0, m = 0, c = 0;
        try { r1 = value1.toString().split(".")[1].length; } catch (e) { r1 = 0; }
        try { r2 = value2.toString().split(".")[1].length; } catch (e) { r2 = 0; }
        c = Math.abs(r1 - r2);
        m = Math.pow(10, Math.max(r1, r2));
        if (c > 0) {
            let cm = Math.pow(10, c);
            if (r1 > r2) {
                value1 = Number(value1.toString().replace(".", ""));
                value2 = Number(value2.toString().replace(".", "")) * cm;
            } else {
                value1 = Number(value1.toString().replace(".", "")) * cm;
                value2 = Number(value2.toString().replace(".", ""));
            }
        } else {
            value1 = Number(value1.toString().replace(".", ""));
            value2 = Number(value2.toString().replace(".", ""));
        }
        return (value1 + value2) / m;
    }

    // 减
    public static sub(value1: number, value2: number) {
        let num = 0, num1 = 0, num2 = 0;
        let precision = 0;// 精度
        try { num1 = value1.toString().split(".")[1].length; } catch (e) { num1 = 0; }
        try { num2 = value2.toString().split(".")[1].length; } catch (e) { num2 = 0; }
        num = Math.pow(10, Math.max(num1, num2));
        precision = (num1 >= num2) ? num1 : num2;
        return ((value1 * num - value2 * num) / num).toFixed(precision);
    }

    // 乘
    public static multi(value1: number, value2: number) {
        let baseData = 0;
        try { baseData += value1.toString().split(".")[1].length; } catch (e) { }
        try { baseData += value2.toString().split(".")[1].length; } catch (e) { }
        return Number(value1.toString().replace(".", "")) * Number(value2.toString().replace(".", "")) / Math.pow(10, baseData);
    }

    // 除
    public static division(value1: number, value2: number) {
        let t1 = 0, t2 = 0, r1 = 0, r2 = 0;
        try {
            t1 = new String(value1).split(".")[1].length;
        } catch (e) { }
        try {
            t2 = value2.toString().split(".")[1].length;
        } catch (e) { }
        r1 = Number(value1.toString().replace(".", ""));
        r2 = Number(value2.toString().replace(".", ""));
        //放大倍数后两个数相除后，乘以两个小数位数长度相减后的10的次幂
        let newData = this.multi((r1 / r2), Math.pow(10, t2 - t1));
        //保留2个小数位数：return newData.toFixed(2)
        return newData;
    }
}